import 'dart:io';

import 'package:flutter/material.dart' hide NavigationBar;
import 'package:hi_base/view_util.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:provider/provider.dart';
import 'package:smart/http/dao/video_detail_dao.dart';
import 'package:smart/model/video_detail_mo.dart';
import 'package:smart/model/video_model.dart';
import 'package:smart/provider/theme_provider.dart';
import 'package:smart/widget/expandable_content.dart';
import 'package:smart/widget/video_header.dart';
import 'package:smart/widget/video_large_card.dart';

import '../http/dao/favorite_dao.dart';
import '../util/toast.dart';
import '../widget/appbar.dart';
import '../widget/hi_tab.dart';
import '../widget/navigation_bar.dart';
import '../widget/video_toolbar.dart';
import '../widget/video_view.dart';

class VideoDetailPage extends StatefulWidget {
  final VideoModel videoModel;

  VideoDetailPage(this.videoModel);

  /* const VideoDetailPage({super.key} this.videoModel);*/

  @override
  State<VideoDetailPage> createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage>
    with TickerProviderStateMixin {
  var tabs = ['简介', '评论999+'];
  TabController? _controller;
  VideoDetailMo? videoDetailMo;
  VideoModel? videoModel;
  List<VideoModel> videoList = [];

  @override
  void initState() {
    super.initState();
    //黑色状态栏，仅Android
    /* changeStatusBar(
        color: Colors.black, statusStyle: StatusStyle.LIGHT_CONTENT);*/
    _controller = TabController(length: tabs.length, vsync: this);
    videoModel = widget.videoModel;
    _loadDetail();
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    context.read<ThemeProvider>().setTheme(ThemeMode.dark);
    return Scaffold(
      //  appBar: AppBar(),
      body: MediaQuery.removePadding(
        removeTop: Platform.isIOS,
        context: context,
        child: videoModel?.url != null
            ? Column(
                mainAxisSize: MainAxisSize.max,
                children: [
                  NavigationBar(
                    // 顶部防止黑色条，防止视频顶部遮挡住了
                    color: Colors.black,
                    statusStyle: StatusStyle.LIGHT_CONTENT,
                    height: Platform.isAndroid ? 0 : 46,
                  ),
                  _buildVideoView(),
                  _buildTabNavigation(),
                  Flexible(
                      child: TabBarView(controller: _controller, children: [
                    _buildDetailList(),
                    Container(
                      child: Text('敬请期待'),
                    )
                  ]))
                ],
              )
            : Container(
                child: Text('敬请期待',
                    style: TextStyle(fontSize: 12, color: Colors.pink)),
              ),
      ),
    );
  }

  _buildVideoView() {
    var model = videoModel;
    return VideoView(model?.url ?? '',
        cover: model?.cover, overlayUI: videoAppBar());
  }

  _buildTabNavigation() {
    return Material(
      //extends StatefulWidget Material 容器
      elevation: 5, //阴影的大小
      shadowColor: Colors.grey[100], //阴影的颜色
      child: Container(
        alignment: Alignment.center,
        height: 39,
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _tabBar(),
            Padding(
              padding: EdgeInsets.only(right: 20), ////距离边缘间距，
              child: Icon(
                Icons.live_tv_rounded,
                color: Colors.grey,
              ),
            )
          ],
        ),
      ),
    );
  }

  _tabBar() {
    return HiTab(
      tabs.map<Tab>((name) {
        return Tab(text: name);
      }).toList(),
      controller: _controller,
      fontSize: 16,
      boderWidth: 3,
      unselectedLabelColor: Colors.black54,
      insets: 13,
    );
  }

  _buildDetailList() {
    return ListView(
      padding: EdgeInsets.all(0),
      children: [...buildContents(), ...buildVideoList()],
    );
  }

  buildContents() {
    return [
      VideoHeader(
        owner: videoModel!.owner,
      ),
      ExpandableContent(
        model: videoModel!,
      ),
      VideoToolBar(
        detailMo: videoDetailMo,
        videoModel: videoModel!,
        onLike: _doLike,
        onUnLike: _onUnLike,
        onCoin: _onCoin,
        onFavorite: _onFavorite,
        onShare: _onShare,
      )
    ];
  }

//    videoDetailDao=
  void _loadDetail() async {
    print('加载数据 loadData');
    try {
      VideoDetailMo result = await VideoDetailDao.get(videoModel!.vid);
      print('loadData:$result');
      setState(() {
        videoDetailMo = result;
        videoModel = result.videoInfo;
        videoList = result.videoList;
      });
    } on NeedAuth catch (e) {
      print('VideoDetailMo   NeedAuth ');
      print(e);
      //  _isLoading = false;
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print('VideoDetailMo   HiNetError ');
      print(e);
      //_isLoading = false;
      showWarnToast(e.message);
    }
  }

  void _doLike() {
    print('_doLike');
  }

  void _onUnLike() {
    print('_onUnLike');
  }

  void _onCoin() {
    print('_onCoin');
  }

  void _onFavorite() async {
    print('_onFavorite 收藏');
    //FavoriteDao
    try {
      var result = await FavoriteDao.favorite(
          videoModel!.vid, !videoDetailMo!.isFavorite);
      print(result);
      videoDetailMo!.isFavorite = !videoDetailMo!.isFavorite;
      if (videoDetailMo!.isFavorite) {
        videoModel!.favorite += 1;
      } else {
        videoModel!.favorite -= 1;
      }
      setState(() {
        videoDetailMo = videoDetailMo;
        videoModel = videoModel;
      });
      showToast(result['msg']);
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print(e);
    }
  }

  void _onShare() {
    print('_onShare');
  }

  buildVideoList() {
    return videoList
        .map((VideoModel mo) => VideoLargeCard(videoModel: mo))
        .toList();
  }
}
